<template>
  <!-- 中间表单内容 -->
  <el-form
    class="pcForm"
    :ref="formConf.formRef"
    :size="formConf.size"
    :model="formModel"
    :label-position="formConf.labelPosition"
    :disabled="formConf.disabled"
    :label-width="formConf.labelWidth + 'px'"
  >
    <form-row-container
      :list.sync="list"
      :formConf="formConf"
      :isEdit="false"
      enabled
    />
    <!-- <el-form-item v-if="formConf.formBtns">
      <el-button type="primary" @click="validateForm(() => {})">提交</el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form-item> -->
  </el-form>
</template>

<script>
import { deepClone, toCamelCase, traverseTree } from "../utils/index";
export default {
  name: "pcForm",
  props: {
    formList: {
      type: Array,
      default: () => [],
    },
    formConf: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      formModel: {},
      list: [],
    };
  },

  watch: {
    formList: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (newValue) {
          this.list = deepClone(newValue);
        }
      },
    },
    list: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (newValue) {
          // 根据表单列表生成动态表单模型数据
          this.getFormModel(newValue);
        }
      },
    },
  },

  methods: {
    toCamelCase,
    // 根据表单列表生成动态表单模型数据
    getFormModel(list) {
      list.forEach((el) => {
        if (el.__vModel__) {
          let obj = JSON.parse(JSON.stringify(this.formModel));
          this.formModel = Object.assign(obj, {
            [el.__vModel__]: el.__config__.defaultValue,
          });
        }
        if (el.__config__.children) {
          this.getFormModel(el.__config__.children);
        }
      });
    },
    submitForm(cb) {
      this.$emit("update:formList", this.list);
      this.$emit("submit", this.list);
      cb(this.formModel, deepClone(this.list));
    },
    validateForm(cb) {
      this.$emit("update:formList", this.list);
      this.$refs[this.formConf.formRef].validate((valid) => {
        this.$emit("submit", this.list);
        // 可以从外部传递方法
        cb(valid, this.formModel, deepClone(this.list));
      });
    },
    // 重置
    resetForm() {
      this.$refs[this.formConf.formRef].resetFields();
      traverseTree(this.list, (node) => {
        node.__config__.defaultValue = null;
      }); // 从根节点开始遍历整个树
      this.$emit("update:formList", this.list);
    },
  },
};
</script>

<style lang="scss">
.pcForm .drawing-item {
  cursor: auto;
}
</style>
